import os
import subprocess
import sys
import time
from pathlib import Path

def check_adb_server():
    """检查ADB服务器是否已经启动"""
    try:
        result = subprocess.run(['adb', 'devices'], 
                              capture_output=True, 
                              text=True, 
                              timeout=10)
        # 如果命令执行成功且输出中包含"daemon started"或设备列表，说明服务器正常
        if result.returncode == 0 and 'List of devices' in result.stdout:
            print("✓ ADB服务器已经在运行")
            return True
        else:
            print("✗ ADB服务器未正常运行")
            return False
    except (subprocess.SubprocessError, FileNotFoundError):
        print("✗ 无法执行adb命令")
        return False

def setup_environment():
    """设置环境变量，将platform-tools目录添加到PATH"""
    current_dir = Path(os.getcwd())
    platform_tools_dir = current_dir / 'platform-tools'
    
    if platform_tools_dir.exists():
        # 将platform-tools目录添加到PATH环境变量
        adb_path = str(platform_tools_dir)
        os.environ['PATH'] = adb_path + os.pathsep + os.environ.get('PATH', '')
        print(f"✓ 已添加platform-tools到PATH: {adb_path}")
        return platform_tools_dir
    else:
        print("✗ 未找到platform-tools目录")
        return None

def start_adb_server(platform_tools_dir):
    """启动ADB服务器"""
    try:
        # 使用绝对路径调用adb程序
        adb_executable = platform_tools_dir / 'adb.exe'
        
        if not adb_executable.exists():
            print(f"✗ 未找到adb可执行文件: {adb_executable}")
            return False
        
        print("正在启动ADB服务器...")
        
        # 启动ADB服务器
        result = subprocess.run([str(adb_executable), 'start-server'], 
                              capture_output=True, 
                              text=True, 
                              timeout=30)
        
        if result.returncode == 0:
            print("✓ ADB服务器启动成功")
            # 等待一下让服务器完全启动
            time.sleep(2)
            return True
        else:
            print(f"✗ ADB服务器启动失败: {result.stderr}")
            return False
            
    except subprocess.TimeoutExpired:
        print("✗ ADB服务器启动超时")
        return False
    except Exception as e:
        print(f"✗ 启动ADB服务器时发生错误: {e}")
        return False

def verify_adb_connection():
    """验证ADB连接是否正常工作"""
    try:
        result = subprocess.run(['adb', 'devices', '-l'], 
                              capture_output=True, 
                              text=True, 
                              timeout=10)
        
        if result.returncode == 0:
            print("ADB设备列表:")
            print(result.stdout)
            return True
        else:
            print(f"ADB设备列表获取失败: {result.stderr}")
            return False
    except Exception as e:
        print(f"验证ADB连接时发生错误: {e}")
        return False

def setup_adb():
    """设置ADB环境"""
    print("=== ADB环境设置 ===")
    platform_tools_dir = setup_environment()
    if not platform_tools_dir:
        print("环境设置失败，程序退出")
        return False

    if check_adb_server():
        print("ADB服务器状态正常")
        return True

    if start_adb_server(platform_tools_dir):
        time.sleep(1)
        if check_adb_server():
            print("✓ ADB服务器启动并运行正常")
            verify_adb_connection()
            return True
        else:
            print("✗ ADB服务器启动后检查失败")
            return False
    
    print("ADB服务器启动失败，程序退出")
    return False